<template>
  <a-button 
    type="primary" 
    :loading="loading"
    @click="handleExecute"
  >
    执行任务
  </a-button>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { message, Modal } from 'ant-design-vue';
import xxlJobApi from '../utils/xxlJobApi';

// 定义组件属性
interface Props {
  taskId?: string | number;
  taskName?: string;
  jobGroup?: string;
  jobDesc?: string;
}

// 定义组件事件
interface Emits {
  (e: 'success'): void;
  (e: 'error', error: string): void;
}

const props = withDefaults(defineProps<Props>(), {
  taskId: '',
  taskName: '定时任务',
  jobGroup: '5',
  jobDesc: '处理委案和委案撤案的任务'
});

const emit = defineEmits<Emits>();

// 加载状态
const loading = ref(false);

// 处理执行任务
const handleExecute = () => {
  Modal.confirm({
    title: '确认执行',
    content: `确定要执行任务"${props.taskName}"吗？`,
    okText: '执行',
    cancelText: '取消',
    onOk: async () => {
      await executeTask();
    }
  });
};

// 执行任务
const executeTask = async () => {
  loading.value = true;
  
  try {
    // 如果没有传入taskId，先获取任务列表找到对应的任务
    let taskId: string | number = props.taskId;
    
    if (!taskId) {
      const fetchedTaskId = await getTaskId();
      if (fetchedTaskId) {
        taskId = fetchedTaskId;
      }
    }
    
    if (!taskId) {
      message.error('未找到对应的任务');
      emit('error', '未找到对应的任务');
      return;
    }
    
    // 执行任务
    const response = await xxlJobApi.post(
      '/jobinfo/trigger',
      `id=${taskId}`
    );
    
    if (response.data && response.data.code === 200) {
      message.success('任务执行成功');
      emit('success');
    } else {
      const errorMsg = response.data.msg || '未知错误';
      message.error('任务执行失败：' + errorMsg);
      emit('error', errorMsg);
    }
  } catch (error) {
    console.error('执行任务失败:', error);
    const errorMsg = error instanceof Error ? error.message : '执行任务失败，请稍后重试';
    message.error(errorMsg);
    emit('error', errorMsg);
  } finally {
    loading.value = false;
  }
};

// 获取任务ID
const getTaskId = async (): Promise<string | null> => {
  try {
    const response = await xxlJobApi.post(
      '/jobinfo/pageList',
      `jobGroup=${props.jobGroup}&triggerStatus=-1&jobDesc=${props.jobDesc}&executorHandler=&author=&start=0&length=100`
    );
    
    if (response.data && response.data.data && response.data.data.length > 0) {
      // 返回第一个匹配的任务ID
      return response.data.data[0].id;
    }
    
    return null;
  } catch (error) {
    console.error('获取任务列表失败:', error);
    return null;
  }
};
</script>

<style scoped>
/* 组件样式 */
</style>
